<template>
  <div class="container">
    <van-row style="text-align: center;">
      <van-image round width="5rem" height="5rem" :src="imgSrc" />
    </van-row>
    <van-form @submit="login">
      <van-field
        v-model="userForm.number"
        name="学号"
        label="学号"
        placeholder="请输入学号"
        :rules="[{ required: true, message: '请填写学号' }]"
      />
      <van-field
        v-model="userForm.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
      <van-row style="text-align: right; padding: 0 20px;">
        还未注册？点此
        <span style="color: blue" @click="toRegister">注册</span>
      </van-row>
    </van-form>
  </div>
</template>

<script>
import jwt_decode from "jwt-decode";
export default {
  name: "login",
  data() {
    return {
      userForm: {
        number: "",
        password: ""
      },
      imgSrc: require("@/assets/logo.png")
    };
  },
  methods: {
    login() {
      this.$api.post("/api/users/login", this.userForm).then(res => {
        // 登录成功
        const { token } = res.data;
        localStorage.setItem("eleToken", token);

        // 解析token
        const decode = jwt_decode(token);
        // 存储数据
        this.$store.dispatch("setIsAutnenticated", !this.isEmpty(decode));
        this.$store.dispatch("setUser", decode);
        this.$store.dispatch("setUserInfo", decode.id);
        // 页面跳转
        this.$message({
          type: "success",
          message: "登录成功"
        });
        this.$router.push("/");
      });
    },
    toRegister() {
      this.$router.push({ name: "register" });
    },
    isEmpty(value) {
      return (
        value === undefined ||
        value === null ||
        (typeof value === "object" && Object.keys(value).length === 0) ||
        (typeof value === "string" && value.trim().length === 0)
      );
    }
  }
};
</script>

<style lang="less" scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #fff;
}
</style>